package trlygjj.tanruiliyigenjinjin.web.filter;

import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import trlygjj.tanruiliyigenjinjin.domain.SystemMenu;
import trlygjj.tanruiliyigenjinjin.service.ISystemMenuService;
import trlygjj.tanruiliyigenjinjin.util.SystemMenuUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by user on 2018/7/12.
 */
public class ExtendsFormAuthenticationFilter extends FormAuthenticationFilter {
    @Setter
    private ISystemMenuService systemMenuService;
    //覆写登录成功的方法
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //登录成功后,查询出所有的菜单存到session中
        Subject sub = SecurityUtils.getSubject();
        if(sub != null) {
            List<SystemMenu> menus = systemMenuService.queryRootMenu();
            System.out.println(menus);
            SystemMenuUtil.filterMenus(menus);
            sub.getSession().setAttribute(SystemMenuUtil.MENU_IN_SESSION, menus);
        }
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":true,\"msg\":\"登录成功!\",\"total\":0,\"rows\":[]}");
        writer.flush();
        //直接让浏览器响应就好了,不用再跳到具体的访问方法login中了
        return false;
    }
    //覆写登录失败的方法
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write("{\"success\":false,\"msg\":\"登录失败,检查一下你的用户名或者密码呗!\",\"total\":0,\"rows\":[]}");
            writer.flush();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
